/**
 * @project weixin
 * @author ddc <jncpp@qq.com>
 */

var HTTP = require("http");
var UTIL = require("util");
var URL  = require("url");
//var QUERY_STRING = require("querystring");
var EVENT_EMITTER = require("events").EventEmitter;

var CONFIG = require("./config.js").Config;
var LOGGER = require("./config.js").Logger;
var MYSQL_QUERY = require("./http_mysql.js").Query;
var WEIXIN = require("./weixin.js").Weixin;
var XML2JS = require("xml2js").parseString;
//var JS2XML = require("xml");

function HttpServer() {}
UTIL.inherits(HttpServer, EVENT_EMITTER);        // 继承自EventEmitter的原型

exports.HttpServer = HttpServer;

/**
 * 创建http服务器于port端口
 *
 * @param  {Number} port
 */
HttpServer.prototype.createServer = function(port)
{
    var self = this;    // 在外部获取HttpServer本身this
    // 因为若是在内部createServer的参数中使用this,将是指的参数本身
    // this始终指调用函数的对象,这里的createServer由HttpServer

    self.weixin = new WEIXIN();
    // self.weixin.getXiaohuangji("1520", function(err, msg){
    //     if(!err){
    //         LOGGER.info("msg: " + msg);
    //     }else{
    //         LOGGER.error("getXiaohuangji: " + err);
    //     }
    // });
    // self.weixin.getBusInfo(102, false, function(err, list){

    // });

    // 创建http服务
    var server = HTTP.createServer(function(request, response) {
        // request 请求对象 response 响应对象

        request.setEncoding("utf8");
        var req_data = URL.parse(request.url, true);

        // 计算请求处理时间
        var begin_time = Date.now();
        response.once("finish", function(){
            LOGGER.trace(Date.now() - begin_time + " ms");
        });

        switch(req_data.pathname)
        {
            case "/weixin":   // 微信回调地址
            {
                response.writeHead(200, {"Content-Type": "text/html"});

                // GET为微信平台验证消息接口申请
                // POST为微信平台向工作平台服务器推送用户发送的消息
                if(request.method === "GET")
                {
                    if(req_data.query.signature && req_data.query.timestamp
                        && req_data.query.nonce && req_data.query.echostr){
                        // 验证消息接口申请
                        if(self.weixin.checkSignature({
                            signature: req_data.query.signature,          // 微信加密签名，signature结合了开发者填写的token参数和请求中的timestamp参数、nonce参数。
                            timestamp: req_data.query.timestamp,          // 时间戳
                            nonce: req_data.query.nonce,                  // 随机数
                            echostr: req_data.query.echostr               // 随机字符串
                        }))
                        {
                            response.end(req_data.query.echostr);
                        }else{
                            LOGGER.error("check signature error.");
                            response.end();
                        }
                    }
                }else{
                    // 接收消息处理
                    var post_content = "";
                    request.on("data", function(data){
                        post_content += data;
                    });
                    request.on("end", function(){
                        XML2JS(post_content, function (err, result) {
                            if (err) {
                                LOGGER.error(UTIL.format("parse xml[%s] is error[%s].", post_content, UTIL.inspect(err)));
                                response.end();
                            }else{
                                if(!self.weixin.config.userId){
                                    self.weixin.config.userId = result.xml.ToUserName[0];
                                }
                                // 解析并处理消息
                                self.weixin.parse(result.xml, response);
                            }
                        });
                    });
                }
                break;
            }
            default:
                LOGGER.trace("emit request_not_found ", self.emit("request_not_found", req_data, response));
                break;
        }
    }).listen(port);

    server.on("error", function(){
        LOGGER.error(UTIL.format("Listen port error at [%d].", port));
        process.exit(1);
    });

    server.on("listening", function(){
        LOGGER.info("Http server running at http://127.0.0.1:%d/", port);
    });
};

HttpServer.prototype.on("request_not_found", function(req_data, response){
    response.writeHead(404, {"Content-Type": "text/plain"});
    response.end("404 Not Found\n");
});